<template>
    <div class="teacher-manage">
        <div class="page-header">
            <h2>教师管理</h2>
            <div class="header-actions">
                <el-button type="primary" @click="handleAdd">
                    <el-icon>
                        <Plus />
                    </el-icon>
                    添加教师
                </el-button>
                <el-button type="danger" :disabled="!selectedTeachers.length" @click="handleBatchDelete">
                    <el-icon>
                        <Delete />
                    </el-icon>
                    批量删除
                </el-button>
            </div>
        </div>

        <!-- 搜索筛选区域 -->
        <div class="filter-container">
            <el-form :inline="true" :model="searchForm" class="search-form">
                <el-form-item label="姓名">
                    <el-input v-model="searchForm.name" placeholder="请输入姓名" clearable />
                </el-form-item>
                <el-form-item label="工号">
                    <el-input v-model="searchForm.teacherId" placeholder="请输入工号" clearable />
                </el-form-item>
                <el-form-item label="院系">
                    <el-select v-model="searchForm.department" placeholder="请选择院系" clearable>
                        <el-option v-for="item in departmentOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">
                        <el-icon>
                            <Search />
                        </el-icon>
                        搜索
                    </el-button>
                    <el-button @click="handleReset">
                        <el-icon>
                            <Refresh />
                        </el-icon>
                        重置
                    </el-button>
                </el-form-item>
            </el-form>
        </div>

        <!-- 表格区域 -->
        <div class="table-container">
            <el-table :data="tableData" border stripe style="width: 100%" @selection-change="handleSelectionChange"
                v-loading="loading">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="id" label="工号" width="120" />
                <el-table-column prop="name" label="姓名" width="100" />
                <el-table-column prop="gender" label="性别" width="80">
                    <template #default="scope">
                        <el-tag :type="scope.row.gender === '男' ? 'primary' : 'success'">
                            {{ scope.row.gender }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="age" label="年龄" width="80" />
                <el-table-column prop="department" label="院系" width="120" />
                <el-table-column prop="title" label="职称" width="120" />
                <el-table-column prop="phone" label="电话" width="140" />
                <el-table-column prop="email" label="邮箱" width="180" />
                <el-table-column prop="address" label="地址" min-width="150" />
                <el-table-column label="操作" width="160" fixed="right">
                    <template #default="scope">
                        <el-button type="primary" size="small" @click="handleEdit(scope.row)">
                            <el-icon>
                                <Edit />
                            </el-icon>
                            编辑
                        </el-button>
                        <el-button type="danger" size="small" @click="handleDelete(scope.row)">
                            <el-icon>
                                <Delete />
                            </el-icon>
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
                    :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                    :total="pagination.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </div>

        <!-- 添加/编辑对话框 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" :close-on-click-modal="false">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="80px" label-position="right">
                <el-form-item label="工号" prop="id">
                    <el-input v-model="form.id" :disabled="isEdit" placeholder="请输入工号" />
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="form.name" placeholder="请输入姓名" />
                </el-form-item>
                <el-form-item label="性别" prop="gender">
                    <el-radio-group v-model="form.gender">
                        <el-radio label="男">男</el-radio>
                        <el-radio label="女">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="年龄" prop="age">
                    <el-input-number v-model="form.age" :min="20" :max="70" placeholder="请输入年龄" />
                </el-form-item>
                <el-form-item label="院系" prop="department">
                    <el-select v-model="form.department" placeholder="请选择院系" style="width: 100%">
                        <el-option v-for="item in departmentOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="职称" prop="title">
                    <el-select v-model="form.title" placeholder="请选择职称" style="width: 100%">
                        <el-option v-for="item in titleOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="电话" prop="phone">
                    <el-input v-model="form.phone" placeholder="请输入电话" />
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="form.email" placeholder="请输入邮箱" />
                </el-form-item>
                <el-form-item label="地址" prop="address">
                    <el-input v-model="form.address" type="textarea" :rows="2" placeholder="请输入地址" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
                        {{ isEdit ? '更新' : '添加' }}
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Delete, Edit, Search, Refresh } from '@element-plus/icons-vue';
import {
    getTeacherList,
    addTeacher,
    updateTeacher,
    deleteTeacher,
    batchDeleteTeachers,
    getDepartmentList,
    getTitleList
} from '@/api/teacher';

// 表格数据
const tableData = ref([]);
const loading = ref(false);
const selectedTeachers = ref([]);

// 搜索表单
const searchForm = reactive({
    name: '',
    teacherId: '',
    department: ''
});

// 分页
const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
});

// 对话框
const dialogVisible = ref(false);
const dialogTitle = ref('');
const isEdit = ref(false);
const submitLoading = ref(false);

// 表单
const formRef = ref(null);
const form = reactive({
    id: '',
    name: '',
    gender: '男',
    age: 30,
    department: '',
    title: '',
    phone: '',
    email: '',
    address: ''
});

// 表单验证规则
const rules = {
    id: [
        { required: true, message: '请输入工号', trigger: 'blur' },
        { pattern: /^\d{6,10}$/, message: '工号为6-10位数字', trigger: 'blur' }
    ],
    name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 2, max: 10, message: '姓名长度在2-10个字符', trigger: 'blur' }
    ],
    gender: [
        { required: true, message: '请选择性别', trigger: 'change' }
    ],
    age: [
        { required: true, message: '请输入年龄', trigger: 'blur' },
        { type: 'number', min: 20, max: 70, message: '年龄在20-70岁之间', trigger: 'blur' }
    ],
    department: [
        { required: true, message: '请选择院系', trigger: 'change' }
    ],
    title: [
        { required: true, message: '请选择职称', trigger: 'change' }
    ],
    phone: [
        { required: true, message: '请输入电话', trigger: 'blur' },
        { pattern: /^1[3456789]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
    ],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
    ],
    address: [
        { required: true, message: '请输入地址', trigger: 'blur' }
    ]
};

// 院系选项 - 优先使用API数据，失败时使用默认选项
const departmentOptions = [
    { value: '计算机学院', label: '计算机学院' },
    { value: '数学学院', label: '数学学院' },
    { value: '物理学院', label: '物理学院' },
    { value: '化学学院', label: '化学学院' },
    { value: '文学院', label: '文学院' },
    { value: '外语学院', label: '外语学院' },
    { value: '经济学院', label: '经济学院' },
    { value: '管理学院', label: '管理学院' }
];

// 获取院系列表数据
const fetchDepartmentData = async () => {
    try {
        const response = await getDepartmentList();
        if (response.data && response.data.length > 0) {
            departmentOptions.splice(0, departmentOptions.length, ...response.data);
        }
    } catch (error) {
        console.error('获取部门列表失败:', error);
        // 开发环境下使用默认选项，不显示错误消息
    }
};

// 职称选项 - 优先使用API数据，失败时使用默认选项
const titleOptions = [
    { value: '助教', label: '助教' },
    { value: '讲师', label: '讲师' },
    { value: '副教授', label: '副教授' },
    { value: '教授', label: '教授' }
];

// 获取职称列表数据
const fetchTitleData = async () => {
    try {
        const response = await getTitleList();
        if (response.data && response.data.length > 0) {
            titleOptions.splice(0, titleOptions.length, ...response.data);
        }
    } catch (error) {
        console.error('获取职称列表失败:', error);
        // 开发环境下使用默认选项，不显示错误消息
    }
};

// 获取教师列表
const getTeacherListData = async () => {
    loading.value = true;
    try {
        // 构建查询参数
        const params = {
            page: pagination.currentPage,
            size: pagination.pageSize,
            name: searchForm.name,
            teacherId: searchForm.teacherId,
            department: searchForm.department
        };

        // 调用API获取数据
        const response = await getTeacherList(params);

        // 更新表格数据和分页信息
        tableData.value = response.data.list || [];
        pagination.total = response.data.total || 0;

    } catch (error) {
        console.error('获取教师列表失败:', error);
        ElMessage.error('获取教师列表失败');
        // 清空数据
        tableData.value = [];
        pagination.total = 0;
    } finally {
        loading.value = false;
    }
};

// 搜索
const handleSearch = () => {
    pagination.currentPage = 1;
    getTeacherListData();
};

// 重置搜索
const handleReset = () => {
    searchForm.name = '';
    searchForm.teacherId = '';
    searchForm.department = '';
    handleSearch();
};

// 表格选择变化
const handleSelectionChange = (selection) => {
    selectedTeachers.value = selection;
};

// 分页大小变化
const handleSizeChange = (size) => {
    pagination.pageSize = size;
    getTeacherListData();
};

// 当前页变化
const handleCurrentChange = (page) => {
    pagination.currentPage = page;
    getTeacherListData();
};

// 添加教师
const handleAdd = () => {
    dialogTitle.value = '添加教师';
    isEdit.value = false;
    dialogVisible.value = true;
    // 重置表单
    Object.keys(form).forEach(key => {
        if (key === 'gender') {
            form[key] = '男';
        } else if (key === 'age') {
            form[key] = 30;
        } else {
            form[key] = '';
        }
    });
};

// 编辑教师
const handleEdit = (row) => {
    dialogTitle.value = '编辑教师';
    isEdit.value = true;
    dialogVisible.value = true;
    // 填充表单数据
    Object.keys(form).forEach(key => {
        form[key] = row[key];
    });
};

// 删除教师
const handleDelete = (row) => {
    ElMessageBox.confirm(`确定要删除教师 ${row.name} 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            // 调用API删除数据
            await deleteTeacher(row.id);
            ElMessage.success('删除成功');
            getTeacherListData();
        } catch (error) {
            console.error('删除失败:', error);
            ElMessage.error('删除失败');
        }
    }).catch(() => {
        // 用户取消删除
    });
};

// 批量删除
const handleBatchDelete = () => {
    if (selectedTeachers.value.length === 0) {
        ElMessage.warning('请选择要删除的教师');
        return;
    }

    ElMessageBox.confirm(`确定要删除选中的 ${selectedTeachers.value.length} 位教师吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            // 获取选中的教师ID列表
            const ids = selectedTeachers.value.map(item => item.id);

            // 调用API批量删除数据
            await batchDeleteTeachers(ids);
            ElMessage.success('批量删除成功');
            getTeacherListData();
        } catch (error) {
            console.error('批量删除失败:', error);
            ElMessage.error('批量删除失败');
        }
    }).catch(() => {
        // 用户取消删除
    });
};

// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return;

    try {
        await formRef.value.validate();
        submitLoading.value = true;

        if (isEdit.value) {
            // 调用API更新数据
            await updateTeacher(form.id, form);
            ElMessage.success('更新成功');
        } else {
            // 调用API添加数据
            await addTeacher(form);
            ElMessage.success('添加成功');
        }

        dialogVisible.value = false;
        getTeacherListData();
    } catch (error) {
        console.error('表单验证失败或提交失败:', error);
        if (error.response && error.response.data && error.response.data.message) {
            ElMessage.error(error.response.data.message);
        } else if (!error.name || error.name !== 'ElMessageBox') {
            // 开发环境下静默处理
            if (!import.meta.env.DEV) {
                ElMessage.error(isEdit.value ? '更新失败' : '添加失败');
            } else {
                ElMessage.success(isEdit.value ? '模拟更新成功' : '模拟添加成功');
                dialogVisible.value = false;

                // 开发环境下模拟更新或添加到列表
                if (isEdit.value) {
                    // 更新现有项
                    const index = tableData.value.findIndex(item => item.id === form.id);
                    if (index !== -1) {
                        tableData.value[index] = { ...form };
                    }
                } else {
                    // 添加新项
                    tableData.value.unshift({ ...form });
                    pagination.total++;
                }
            }
        }
    } finally {
        submitLoading.value = false;
    }
};

// 初始化
onMounted(async () => {
    // 加载院系和职称数据
    await Promise.all([fetchDepartmentData(), fetchTitleData()]);
    // 获取教师列表
    getTeacherListData();
});
</script>

<style scoped>
.teacher-manage {
    padding: 15px;
    background-color: #f0f2f5;
    min-height: calc(100vh - 60px);
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    padding: 0 5px;
}

.header-actions {
    display: flex;
    gap: 10px;
}

.filter-container {
    background-color: #fff;
    padding: 12px;
    border-radius: 4px;
    margin-bottom: 15px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-form .el-form-item {
    margin-bottom: 0;
}

.table-container {
    background-color: #fff;
    padding: 12px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination-container {
    margin-top: 15px;
    display: flex;
    justify-content: flex-end;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .teacher-manage {
        padding: 10px;
    }

    .page-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 15px;
    }

    .header-actions {
        width: 100%;
        justify-content: flex-start;
    }

    .search-form {
        display: flex;
        flex-direction: column;
        gap: 10px;
    }

    .el-form-item {
        margin-right: 0;
        margin-bottom: 0;
    }
}
</style>